<template>
  <ul class="list">
    <li v-for="key in letters"
        :key="key"
        :ref="key"
        @click="handleClick"
        @touchstart="handleStart"
        @touchmove="handleMove"
        @touchend="handleEnd"
    >{{key}}
    </li>
  </ul>
</template>

<script>
  export default {
    props: {
      cities: Object
    },
    data () {
      return {
        touchStatus: false,
        timer: null,
        offsetTop: 0
      }
    },
    updated () {
      this.offsetTop = this.$refs['A'][0].offsetTop
    },
    computed: {
      letters () {
        let result = []
        for (let item in this.cities) {
          result.push(item)
        }
        return result
      }
    },
    methods: {
      handleClick (e) {
        this.$emit('change', e.target.innerText)
      },
      handleStart () {
        this.touchStatus = true
      },
      handleMove (e) {
        // 1. 获取到A距离搜索框的高度
        // 2. 获取滚动位置Y
        // 3. 滚动位置Y-顶部搜索框高度-A到搜索框的高度 = A到滚动字母的距离
        // 4. 3获得到的位置/每个字母高度=滚动字母的索引
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          if (this.touchStatus) {
            const y = e.touches[0].clientY - 74 - this.offsetTop
            const index = Math.floor(y / 20)
            if (this.letters[index]) {
              this.$emit('change', this.letters[index])
            }
          }
        }, 15)
      },
      handleEnd () {
        this.touchStatus = false
      },
    },
  }
</script>

<style lang="stylus" scoped>
  @import "~css/variable.styl"

  .list
    position absolute
    top 1.58rem
    right 0
    bottom 0
    display flex
    flex-direction column
    justify-content center
    width: .4rem
    li
      line-height: .4rem
      color $color-theme
      text-align center
</style>
